package com.citywithincity.utils;



import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

public class FormUploadUtil {
	
	public static class UploadGroup{
		Map<String, Object> data=new HashMap<String, Object>();
		private int fileCount;
		public UploadGroup(){
			
		}
		
		public Map<String, Object> getMap(){
			return data;
		}
		
		public void put(String key,Object value){
			data.put(key, value);
		}
		
		public Object get(String key){
			return data.get(key);
		}
		
		public UploadFile getFile(String key){
			return (UploadFile) data.get(key);
		}
		
		public void put(String key,File file,String uri,String name,String url){
			UploadFile info = new UploadFile(file,uri,name,url);
			data.put(key, info);
			fileCount++;
		}
		
		public int getFileCount(){
			return fileCount;
		}
		
	}
	
	public static class UploadFile{
		private File file;
		private String path;
		private String name;
		private String url;
		
		public UploadFile(File file,String path,String name,String url){
			this.file = file;
			this.path = path;
			this.name = name;
			this.url = url;
		}

		public String getPath() {
			return path;
		}

		public void setPath(String path) {
			this.path = path;
		}

		public File getFile() {
			return file;
		}

		public void setFile(File file) {
			this.file = file;
		}

		public String getName() {
			return name;
		}

		public void setName(String name) {
			this.name = name;
		}
		
		
	}
	
	
	private static DiskFileItemFactory factory = new DiskFileItemFactory();
	private static String uploadDir = ConfigReader.getDefault().get("upload_path");
	private static String uploadContext = ConfigReader.getDefault().get("upload_context");
	
	static{
		if(StringUtils.isEmpty(uploadDir)){
			//默认网站
			uploadDir = PathUtil.getRealPath("src/main/webapp/uploads");
			
		}else{
			if(!uploadDir.endsWith("/")){
				uploadDir = uploadDir+"/";
			}
		}
		
	}
	
	
	public static UploadGroup doUpload(HttpServletRequest request) throws WebError {

		ServletFileUpload upload = new ServletFileUpload(factory);
		upload.setHeaderEncoding("UTF-8");
		if (!ServletFileUpload.isMultipartContent(request)) {
			throw new WebError("请上传文件");
		}
		try {
			UploadGroup data = new UploadGroup();
			List<FileItem> list = upload.parseRequest(request);
			for (FileItem item : list) {
				if (item.isFormField()) {
					String name = item.getFieldName();
					String value = item.getString("UTF-8");
					data.put(name, value);
				} else {
					InputStream in = item.getInputStream();
					StringBuilder dirBuilder = new StringBuilder(uploadDir.length()+64).append(uploadDir).append(File.separator);
					String today = new SimpleDateFormat("yyyy_MM_dd").format(new Date());
					StringBuilder fileNameBuilder = new StringBuilder(uploadContext.length()+64).append(uploadContext).append(today);
					String dir =dirBuilder.append(today).toString();
					File fDir = new File(dir);
					if(!fDir.isDirectory()){
						fDir.mkdir();
					}
					String name = MD5Util.md5Appkey( UUID.randomUUID().toString());
					String fileName = item.getName();
					int dot = fileName.lastIndexOf('.');
					if(dot>0){
						name += fileName.substring(dot);
					}
					fileNameBuilder.append('/').append(name);
					//data.put("fileWebPath", fileNameBuilder.toString());
					File file = new File(fDir,name);
					FileOutputStream outputStream = new FileOutputStream(file);
					IoUtil.copyAndCloseAll(in, outputStream);
					//data.put(item.getFieldName(), file);
					
					data.put(item.getFieldName(), file, fileNameBuilder.toString(),item.getName(),fileNameBuilder.toString());
				}
			}
			return data;
		} catch (Exception e) {
			throw new WebError(e.getMessage());
		}

	}
}
